package com.pp.small.product.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pp.small.product.entity.Product;
import com.pp.small.product.mapper.ProductMapper;
import com.pp.small.product.service.ProductService;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * product信息 服务实现类
 * </p>
 *
 * @author pzh
 * @since 2024-12-12 16:12:35
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public Product saveProduct(Product product) {
        this.save(product);
        // 载入数据到ES
        elasticsearchRestTemplate.save(product);
        return product;
    }

    @Override
    public List<Product> listProduct() {
        SearchHits<Product> searchHits = elasticsearchRestTemplate.search(new NativeSearchQueryBuilder().build(), Product.class);
        if (CollectionUtil.isNotEmpty(searchHits.getSearchHits())) {
            return searchHits.getSearchHits().stream().map(SearchHit::getContent).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public List<Product> listByName(String name) {
        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery("name", name))
                .build();
        SearchHits<Product> searchHits =  elasticsearchRestTemplate.search(nativeSearchQuery, Product.class);
        if (CollectionUtil.isNotEmpty(searchHits.getSearchHits())) {
            return searchHits.getSearchHits().stream().map(SearchHit::getContent).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public Product getProduct(String id) {
        return elasticsearchRestTemplate.get(id, Product.class);
    }
}
